<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="小程序">
                <a-select placeholder="请选择" v-model="queryParam.id" @change="getList()">
                  <a-select-option :value="item.id" v-for="item of idList" :key="item.id">
                    {{ item.app_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="6">
              <a-form-item label="发放时间">
                <a-range-picker
                  allowClear
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryTime"
                  @change="changeTime"
                />
                <!-- @calendarChange="calendarChange" -->
              </a-form-item>
            </a-col>
            <!-- <a-col :span="6">
              <a-form-item label="素材名称">
                <a-input placeholder="请输入素材名称" v-model="queryParam.material_name" allowClear></a-input>
              </a-form-item>
            </a-col> -->

            <a-col :span="6">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <div>
          <a-radio-group v-model="queryParam.status">
            <a-radio-button :value="0"> 全部 </a-radio-button>
            <a-radio-button :value="1"> 活动中 </a-radio-button>
            <a-radio-button :value="2"> 已结束 </a-radio-button>
          </a-radio-group>
        </div>

        <a-button type="primary" @click="$router.push({ name: 'storeCouponEdit' })" icon="plus">新建</a-button>
      </div>

      <a-table
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="record => record.id"
        :pagination="{
          total: this.total,
          pageSize: this.pageSize,
          showSizeChanger: false,
          onChange: this.tablePageChange
        }"
      >
        <span slot="time" slot-scope="text, record">
          {{ record.publish_start_time }}至{{ record.publish_end_time }}
        </span>

        <span slot="activity_name" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">
              {{ text.activity_name }}
            </template>
            <div class="name">
              {{ text.activity_name }}
            </div>
          </a-tooltip>
        </span>

        <span slot="voucher_type" slot-scope="text, record">
          {{ text.voucher_type === 'DISCOUNT_VOUCHER' ? '折扣' : '满减' }}
        </span>

        <span slot="minPrice" slot-scope="text, record">
          {{ getMinPrice(text) }}
        </span>

        <span slot="preferential_amount" slot-scope="text, record">
          {{ getPreferentialAmount(text) }}
        </span>

        <span slot="discount" slot-scope="text, record">
          {{ getDiscount(text) }}
        </span>

        <span slot="created_at" slot-scope="text, record">
          {{ text.created_at | timeFormat }}
        </span>

        <span slot="activity_status" slot-scope="text, record">
          <a-badge :color="getStatus(text.activity_status)[1]" :text="getStatus(record.activity_status)[0]" />
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handle('remove', text)">删除</a>

          <template v-if="text.activity_status === 'ACTIVE'">
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a href="javascript:;" @click="handle('stop', text)">停止活动</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;" @click="handle('create', text)">生成券码</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </a-table>
    </a-card>

    <!-- 新增编辑 -->
    <a-modal
      title="生成商家券码"
      :width="500"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      v-model="visible"
      @ok="handleOk"
    >
      <el-form
        :rules="modifyRules"
        label-width="120px"
        :model="modifyForm"
        label-suffix="："
        ref="modifyForm"
        size="small"
      >
        <el-form-item label="生成数量" prop="count">
          <a-input-number placeholder="请输入" :min="0" :max="1000" v-model="modifyForm.count" />
        </el-form-item>

        <template slot="footer">
          <a-button v-loading="modalLoading" type="primary" @click="handleOk"> 提交 </a-button>
          <a-button style="margin-left: 10px" @click="visible = false"> 取消 </a-button>
        </template>
      </el-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import {
  storeActivityList,
  activityDeliveryStop,
  codecreate,
  codeRefresh,
  stopActivity,
  removeActivity
} from '@/api/marketing/alipayPromotion'
import { alipayList } from '@/api/setting/applet'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100
  },
  {
    title: '名称',
    scopedSlots: {
      customRender: 'activity_name'
    }
  },
  {
    title: '最低消费',
    scopedSlots: {
      customRender: 'minPrice'
    }
  },
  {
    title: '优惠方式',
    scopedSlots: {
      customRender: 'voucher_type'
    }
  },
  {
    title: '优惠金额',
    scopedSlots: {
      customRender: 'preferential_amount'
    }
  },
  {
    title: '折扣',
    scopedSlots: {
      customRender: 'discount'
    }
  },
  {
    title: '发放数量',
    dataIndex: 'summary.publish_count',
    sorter: (a, b) => parseInt(a.summary.publish_count) - parseInt(b.summary.publish_count)
  },
  {
    title: '使用数量',
    dataIndex: 'summary.used_count',
    sorter: (a, b) => parseInt(a.summary.used_count) - parseInt(b.summary.used_count)
  },
  {
    title: '总数量',
    dataIndex: 'voucher_send_rule.voucher_quantity',
    sorter: (a, b) => parseInt(a.voucher_send_rule.voucher_quantity) - parseInt(b.voucher_send_rule.voucher_quantity)
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'activity_status'
    },
    width: 120,
    sorter: (a, b) => a.activity_status - b.activity_status
  },
  {
    title: '发放时间',
    scopedSlots: {
      customRender: 'time'
    },
    width: 200
  },
  {
    title: '创建时间',
    scopedSlots: {
      customRender: 'created_at'
    }
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action'
    },
    width: 150
  }
]

export default {
  data() {
    return {
      queryTime: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,
      idList: [],
      serviceList: [],
      queryParam: {
        publish_start_time: '',
        publish_end_time: '',
        id: '',
        status: 0
      },

      list: [],
      startTime: '',

      modifyForm: {
        count: 1
      },
      modifyRules: {
        count: [{ required: true, message: '请输入卡劵数量', trigger: 'blur' }]
      },
      modalLoading: false,
      visible: false
    }
  },

  watch: {
    visible(_val) {
      if (_val) {
        this.$refs.modifyForm.resetFields()
      }
    }
  },

  computed: {
    getStatus() {
      return status => {
        let text, color
        switch (status) {
          case 'ACTIVE':
            text = '活动中'
            color = 'rgb(101, 200, 23)'
            break

          default:
            text = '已结束'
            color = '#FF4D4F'
            break
        }
        return [text, color]
      }
    },

    getMinPrice() {
      return item => {
        if (item.voucher_type === 'FIX_VOUCHER') {
          return item.voucher_use_rule.fix_voucher.floor_amount || '0.00'
        }

        return item.voucher_use_rule.discount_voucher.floor_amount || '0.00'
      }
    },

    getPreferentialAmount() {
      return item => {
        if (item.voucher_type === 'FIX_VOUCHER') {
          return item.voucher_use_rule.fix_voucher.amount || '0.00'
        }

        return '0.00元'
      }
    },

    getDiscount() {
      return item => {
        if (item.voucher_type === 'FIX_VOUCHER') return '10.0折'

        return item.voucher_use_rule.discount_voucher.discount + '折'
      }
    }
  },

  mounted() {
    const hide = this.$message.loading('加载中', 0)

    alipayList()
      .then(res => {
        hide()
        if (!res.code && res.data && res.data.length) {
          this.idList = res.data
          this.queryParam.id = res.data[0].id
          this.getList()
        }
      })
      .catch(err => {
        hide()
      })
  },

  methods: {
    handle(type, { alipay_activity_id, mini_id, id }) {
      const hide = this.$message.loading('加载中', 0)

      switch (type) {
        case 'remove':
          removeActivity({
            alipay_activity_id,
            id: mini_id
          })
            .then(res => {
              hide()
              if (!res.code) {
                this.$message.success('操作成功~')
                this.getList()
                return
              }
              this.$message.error(res.msg)
            })
            .catch(() => {
              hide()
            })
          break

        case 'stop':
          stopActivity({ alipay_activity_id, id: mini_id })
            .then(res => {
              hide()

              if (!res.code) {
                this.$message.success('操作成功~')
                this.getList()
                return
              }
              this.$message.error(res.msg)
            })
            .catch(() => {
              hide()
            })
          break

        case 'create':
          hide()

          this.modifyForm = {
            count: 1,
            activity_ordervoucher_id: id,
            id: mini_id
          }
          this.alipay_activity_id = alipay_activity_id
          this.visible = true
          break
      }
    },

    handleOk() {
      this.$refs.modifyForm.validate(async valid => {
        if (valid) {
          this.modalLoading = true

          const res = await codecreate(this.modifyForm)
          if (res.code) {
            this.modalLoading = false
            return
          }

          const res2 = await codeRefresh({
            alipay_activity_id: this.alipay_activity_id,
            id: this.modifyForm.id
          })
          this.modalLoading = false

          if (!res2.code) {
            this.$message.success(res.msg)
            this.visible = false
            this.getList()
            return
          }

          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 切换筛选时间
    changeTime(e) {
      if (e.length) {
        this.queryParam.delivery_begin_time = e[0]
        this.queryParam.delivery_end_time = e[1]
      } else {
        this.queryParam.delivery_begin_time = ''
        this.queryParam.delivery_end_time = ''
      }
    },

    // 获取数据列表
    async getList(page = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await storeActivityList({
        ...queryParam,
        pageSize: String(pageSize),
        page: String(page)
      })

      if (res.code == 0) {
        let { count: total, data: list } = res
        this.total = total
        this.list = list || []
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 点击单个
    handleItem(type, { id }) {
      switch (type) {
        case 'stop':
          activityDeliveryStop(id).then(res => {
            if (!res.code) {
              this.$message.success(res.msg)
              this.getList()
              return
            }

            this.$message.error(res.msg)
          })
          break
      }
    }
  }
}
</script>

<style lang="less" scoped>
.name {
  width: 160px;
}
</style>
